package com.penghaonan.appframework.utils.monitor;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;

import com.penghaonan.appframework.AppDelegate;
import com.penghaonan.appframework.utils.Logger;

public class BatteryMonitor extends AMonitor<BatteryMonitor.BatteryInfo> {

    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            onBatteryIntentReceived(intent);
        }
    };
    private final BatteryInfo batteryInfo = new BatteryInfo();

    public BatteryMonitor() {
        Intent intent = AppDelegate.getApp().registerReceiver(receiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        onBatteryIntentReceived(intent);
    }

    @Override
    public BatteryInfo getValue() {
        return batteryInfo;
    }

    @Override
    public void release() {
        super.release();
        AppDelegate.getApp().unregisterReceiver(receiver);
    }

    private void onBatteryIntentReceived(Intent intent) {
        if (intent == null) {
            return;
        }
        batteryInfo.level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        batteryInfo.total = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        batteryInfo.status = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, BatteryManager.BATTERY_STATUS_UNKNOWN);
        Logger.i("onBatteryIntentReceived : " + batteryInfo.toString());
        notifyListeners();
    }

    public static class BatteryInfo {
        private int level;
        private int status;
        private int total;

        public String getPercentText() {
            if (total <= 0) {
                total = 100;
            }
            return (level * 100 / total) + "%";
        }

        public float getLevel() {
            return (float) level / total;
        }

        public int getStatus() {
            return status;
        }

        public boolean isCharging() {
            return status == BatteryManager.BATTERY_STATUS_CHARGING
                    || status == BatteryManager.BATTERY_STATUS_FULL
                    || status == BatteryManager.BATTERY_STATUS_UNKNOWN;
        }

        @Override
        public String toString() {
            return "BatteryInfo{" +
                    "level=" + level +
                    ", status=" + status +
                    ", total=" + total +
                    '}';
        }
    }
}
